/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
 * Description: Hmfs-tools device manager
 */

#ifndef DEVICE_MANAGER_H
#define DEVICE_MANAGER_H

#include <memory>
#include <string>
#include <sys/stat.h>
#include <sys/types.h>

#include "hmfs_command.h"
#include "hmfs_fs.h"

namespace OHOS {
namespace Hmfs {
struct DeviceInfo {
    std::string path;
    int32_t fd = -1;
    uint32_t sectorSize = DEFAULT_SECTOR_SIZE;
    uint64_t sectorCount;
    uint64_t startBlockId;
    uint64_t endBlockId;
    uint32_t segmentCount;
    bool isMetaDevice = false;

    int32_t zonedModel;
    uint32_t zoneCount;
    uint32_t randomZonesCount;
    size_t zoneBlocks;
    uint64_t zoneSize;
    std::unique_ptr<size_t[]> zoneCapBlocks = nullptr;

    ~DeviceInfo()
    {
        if (fd > 0) {
            (void)close(fd);
        }
    }
};

class DeviceManager {
public:
    ~DeviceManager() = default;

    static DeviceManager &GetInstance();
    int32_t CreateDeviceInfo(std::string &path, bool isMetaDevice);
    DeviceInfo *GetDeviceInfo(uint32_t deviceId);
    uint32_t GetDeviceCount();
    bool CheckDeviceFormated();
    int32_t TrimDevices();
    uint64_t GetTotalSectors();
    bool IsDeviceMounted(std::string &path);

private:
    explicit DeviceManager(CmdConfig &cmdPara) : cmdPara_(cmdPara) {};
    int32_t TrimDevice(DeviceInfo *deviceInfo);
    int32_t CreateDeviceInfoPart1(std::unique_ptr<DeviceInfo> &device, struct stat *statInfo, bool isMetaDevice);
    int32_t CreateDeviceInfoPart2(std::unique_ptr<DeviceInfo> &device);
    bool IsMounted(const char *mountPoint, std::string &device);
    bool IsRootDevice(std::string &path);

    std::vector<std::unique_ptr<DeviceInfo>> devices_;
    uint64_t totalSectors_ = 0;
    CmdConfig &cmdPara_;
};

} // namespace Hmfs
} // namespace OHOS
#endif
